package com.xuan.juc.forkjoin;

import java.util.concurrent.RecursiveTask;

/*
* 求和计算的任务
*
* 如何使用forkjoin
* 1 forkjoinpool 通过它来执行
* 2 计算任务 forkjoinPool.execute(ForkJoinTask task)
* */
public class ForkJoinTest extends RecursiveTask<Long> {
    private long start;
    private long end;

    private long temp = 100L;
    public ForkJoinTest(long start,long end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum=0L;
        if((end - start)>temp){
            // 分支合并
            long mid = (start + end)/2;
            ForkJoinTest forkJoinTest1 = new ForkJoinTest(start, mid);
            forkJoinTest1.fork(); //拆分任务 把任务压入线程队列
            ForkJoinTest forkJoinTest2 = new ForkJoinTest(mid+1, end);
            forkJoinTest2.fork();

            sum = forkJoinTest1.join() + forkJoinTest2.join();

        }else{

            for (long i = 0; i < 10000; i++) {
                sum=sum+i;
            }

        }
        return sum;
    }
}
